package com.agnes.network.observer;

import android.text.TextUtils;

import com.agnes.network.Const;
import com.agnes.network.callback.RespCallback;
import com.agnes.network.util.JsonUtils;

import io.reactivex.disposables.CompositeDisposable;
import org.json.JSONObject;

/**
 * Desc:  接收JSONObject 数据格式，返回的 data 为JSONObject格式
 * Creator ling
 * Date:   2017/9/28 0028 15:17
 */

public class JOObserver extends ApiObserver<JSONObject> {

    public JOObserver(RespCallback<JSONObject> responseCallback,
        CompositeDisposable compositeDisposable) {
        super(responseCallback, compositeDisposable);
    }

    @Override
    public void onSuccess(String response) {
        JSONObject rootJO = JsonUtils.parseJO(response);
        if (rootJO != null) {
            String code = rootJO.optString(Const.KEY_CODE);
            String msg = rootJO.optString(Const.KEY_MSG);
            String data = rootJO.optString(Const.KEY_DATA);
            if (TextUtils.isEmpty(data)) {
                data = "{}";
            }

            if (JsonUtils.isJOFormat(data)) {
                JSONObject dataJson = JsonUtils.parseJO(data);
                if (Const.SUCCESS_CODE.equals(code)) {
                    mResponseCallback.onSuccess(msg, dataJson);
                } else {
                    mResponseCallback.onError(code, msg, dataJson);
                }
            } else {
                onFailure("data is not json object format!!!");
            }
        } else {
            onFailure("result is not json object format!!!");
        }
    }
}
